﻿using System;
using System.Diagnostics;

namespace InterfacesPhoneCommands
{
    public abstract class WcfWindowsServicesHost : IService
    {
        private readonly string _nameService = "";
        private bool _isInit;

        private bool _isRunning;
        private System.ServiceModel.ServiceHost _serviceHost;

        protected WcfWindowsServicesHost(Type serviceType)
        {
            _serviceHost = new System.ServiceModel.ServiceHost(serviceType);
            _nameService = serviceType.FullName;
        }

        #region IService Members

        public String NameService()
        {
            return _nameService;
        }

        public virtual void InitService()
        {
            _isInit = true;
            _isRunning = false;
            Start();
        }

        public virtual void Start()
        {
            if (!_isInit || _isRunning)
            {
            }
            else
            {
                try
                {
                    _serviceHost.Open();
                    _isRunning = true;
                }
                catch (Exception ex)
                {
                    CriticalError = ex;
                    EventLog.WriteEntry("FC.Shared.FC.Shared.Library", ex.ToString(), EventLogEntryType.Error, 0);
                    _serviceHost = null;
                }
            }
        }

        public virtual void Stop()
        {
            if (_serviceHost != null)
            {
                _serviceHost.Close();
            }
            _serviceHost = null;
            _isRunning = false;
        }

        public virtual bool IsRunning()
        {
            return _isRunning && CriticalError == null;
        }

        public Exception CriticalError { get; private set; }

        #endregion

        public System.ServiceModel.ServiceHost ServiceHost()
        {
            return _serviceHost;
        }
    }
}